﻿
using System;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Distributed;
/// <summary>
/// 登录判断
/// </summary>
namespace Web.Filters
{

    public class MyIsLoginFilter : Attribute, IActionFilter
    {
        private readonly IDistributedCache _cache;

        public bool IsCheck { get; set; }

        public MyIsLoginFilter(IDistributedCache cache)
        {
            _cache = cache;
        }

        public void OnActionExecuted(ActionExecutedContext context)//方法执行后执行
        {

        }

        public void OnActionExecuting(ActionExecutingContext context)//方法执行前执行
        {
           /* try
            {
                //权限验证
                //如果登录的用户名为admin2929，则拥有所有的权限
                HttpRequest request = context.HttpContext.Request;
                string accessToken = request.Headers["Access_Token"];//获取 post页面中heder中的token

                string controller = context.RouteData.Values["Controller"].ToString();
                string action = context.RouteData.Values["Action"].ToString();
                List<string> execList = new List<string> { "login", "introduce" };
                if (!execList.Contains(controller.ToLower()))//不为登录页面 和 相关介绍页面
                {
                    //判断是否需要登录
                    var canLogin = ConfigHelper.GetSection("CanLogin");
                    if (canLogin.ToLower().Equals("true"))
                    {
                        #region  session 检查  是否登录超时,默认为30分钟，在startup里设置  
                        context.HttpContext.Session.TryGetValue(Utility.AccessToken.AccessTokenName, out Byte[] sessionBytes);
                        if (sessionBytes != null)
                        {
                            string sessionValue = System.Text.Encoding.Default.GetString(sessionBytes);
                            context.HttpContext.Request.Cookies.TryGetValue(Utility.AccessToken.AccessTokenName, out string CookieValue);

                            if (!sessionValue.Equals(CookieValue))//如果为空，或者session和cookie不一致,则跳转到登录页
                            {
                                context.Result = new EmptyResult(); //防止执行后续的代码
                                context.HttpContext.Response.Redirect("/Login/Index");
                            }else
                            {
                                //每次操作都重新写入session,30分钟无操作需重新登录
                                context.HttpContext.Session.Set(Utility.AccessToken.AccessTokenName, sessionBytes);
                            }
                        }
                        else
                        {
                            context.Result = new EmptyResult(); //防止执行后续的代码
                            context.HttpContext.Response.Redirect("/Login/Index");
                        }
                        #endregion
                    }
                }
            }
            catch (Exception )
            {
                throw new NotImplementedException();
            }*/
        }
    }
}
